package com.ruoyi.web.message.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.message.domain.Message;
import com.ruoyi.web.message.domain.MessageUser;
import com.ruoyi.web.message.dto.SendMessageVo;
import com.ruoyi.web.message.dto.UserMessageDto;
import com.ruoyi.web.message.mapper.MessageMapper;
import com.ruoyi.web.message.mapper.MessageUserMapper;
import com.ruoyi.web.message.service.IMessageUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息发送列Service业务层处理
 *
 * @author 范书铭
 * @date 2024-10-11
 */
@Service
public class MessageUserServiceImpl extends ServiceImpl<MessageUserMapper, MessageUser> implements IMessageUserService {
    @Autowired
    private MessageUserMapper messageUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Resource
    private MessageMapper messageMapper;


    /**
     * 查询消息发送列列表
     *
     * @param messageUser 消息发送列
     * @return 消息发送列
     */
    @Override
    public List<MessageUser> selectMessageUserList(MessageUser messageUser) {
        return messageUserMapper.selectMessageUserList(messageUser);
    }

    @Transactional
    @Override
    public boolean send(SendMessageVo sendMessageDto) {
        List<Long> deptToUserIds = sysUserMapper.getUserByDeptIds(sendMessageDto.getDeptIds())
                .stream().map(SysUser::getUserId).collect(Collectors.toList());
        deptToUserIds.addAll(sendMessageDto.getUserIds());
        List<MessageUser> messageUsers = deptToUserIds.stream()
                .map(aLong -> {
                    MessageUser messageUser = new MessageUser();
                    messageUser.setUserId(aLong);
                    messageUser.setMessageId(sendMessageDto.getMessageId());
                    return messageUser;
                }).collect(Collectors.toList());
        return saveBatch(messageUsers, 20);
    }

    @Override
    public List<UserMessageDto> listUserMessage(Long userId,Boolean isRead) {
        List<UserMessageDto> messages = messageMapper.selectUserMessage(userId,isRead);
        return messages;
    }
}